package com.briup.cloud.framework.resource.web.controller;

import com.briup.cloud.framework.resource.web.vm.UserTokenVM;
import com.briup.cloud.framework.resource.web.rest.RemoteService;
import com.briup.framework.utils.common.EntityUtils;
import com.briup.framework.utils.web.Response;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author guomiao
 *
 * @Date 2022/3/21 11:27
 */
@Api(tags = "0.1.认证模块")
@RestController
@RequestMapping("/uaa")
public class AuthController {

    @Value("${security.oauth2.client.client-id}")
    private String clientId;

    @Value("${security.oauth2.client.client-secret}")
    private String clientSecret;

    @Autowired
    private RemoteService remoteService;
    @ApiOperation("登录")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "username",value = "用户名",defaultValue = "admin",dataTypeClass = String.class),
        @ApiImplicitParam(name = "password",value = "密码",defaultValue = "admin",dataTypeClass = String.class)
    })
    @PostMapping("/login")
    public Response<UserTokenVM> login(String username, String password){
        Map<String,String> params = new HashMap<>();
        params.put("client_id",clientId);
        params.put("client_secret",clientSecret);
        params.put("username",username);
        params.put("password",password);
        params.put("grant_type","password");
        ResponseEntity<OAuth2AccessToken> result = remoteService.postAccessToken(
                new UsernamePasswordAuthenticationToken(username,password),params);
        System.out.println("结果："+result);
        OAuth2AccessToken token = result.getBody();
        UserTokenVM vm = EntityUtils.entity2VM(token,UserTokenVM.class);
        vm.setUsername(username);
        vm.setScope(token.getScope());
        vm.setExpiresIn(token.getExpiresIn());
        vm.setAccessToken(token.getTokenType()+" "+token.getValue());
        return Response.success(vm);
    }


}
